//
//  WebViewController.m
//  iOS-CtrlV
//
//  Created by Wang Li on 13-1-12.
//  Copyright (c) 2013年 Wang Li. All rights reserved.
//

#import "WebViewController.h"
#import "ASIHTTPRequest.h"
#import "CJSONDeserializer.h"
#import "MainTabBarController.h"
#import "RegisterViewController.h"
@interface WebViewController ()

@end

@implementation WebViewController
@synthesize m_RequestString;
@synthesize m_CallString;
@synthesize m_BangType;
@synthesize m_NeedLogin;
- (id)init
{
    if (self = [super init]) {
        // Custom initialization
        _AppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
        self.m_NeedLogin =NO;
    }
    return self;
}

-(void) dealloc
{
    [_BackBttBarItem release];
    [m_RequestString release];
    [m_CallString release];
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    _BackBttBarItem =[UIButton buttonWithType:UIButtonTypeCustom];
    _BackBttBarItem.frame =CGRectMake(0, 0, 44, 44);
    [_BackBttBarItem setImage:[UIImage imageNamed:@"navback.png"] forState:UIControlStateNormal];
    [_BackBttBarItem addTarget:self action:@selector(navBackBtt) forControlEvents:UIControlEventTouchUpInside];
    [_BackBttBarItem retain];
    [self.navigationController.navigationBar addSubview:_BackBttBarItem];
    
    // Do any additional setup after loading the view.
    UIWebView* tWebView =[[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 480-20-44)];
    [tWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:m_RequestString]]];
    tWebView.delegate = self;
    [self.view addSubview:tWebView];
    [tWebView release];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void) viewWillDisappear:(BOOL)animated
{
    [_BackBttBarItem removeFromSuperview];
}

-(void) viewWillAppear:(BOOL)animated
{
    if ([_BackBttBarItem superview] ==nil) {
        [self.navigationController.navigationBar addSubview:_BackBttBarItem];
    }
    if (m_NeedLogin) {
        m_NeedLogin = NO;
        [self.navigationController popViewControllerAnimated:NO];
    }
}

-(void) viewDidAppear:(BOOL)animated
{

}

//退出
-(void) navBackBtt
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (NSString*) decodeFromPercentEscapeString:(NSString *) string {
    return ( NSString *) CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL,
                                                                                         ( CFStringRef) string,
                                                                                         CFSTR(""),
                                                                                         kCFStringEncodingUTF8);
}

#pragma mark-
#pragma mark UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSLog(@"%@",[request.URL absoluteString]);
    NSString* tULRStr = [request.URL absoluteString];
    if ([tULRStr rangeOfString:m_CallString].location != NSNotFound) {
        NSLog(@"login ok to");
        tULRStr =(NSString*) CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, ( CFStringRef) tULRStr, CFSTR(""), kCFStringEncodingUTF8);
        NSLog(@"%@",tULRStr);
        int tCutStart = [tULRStr rangeOfString:@"?"].location;
        tCutStart++;
        NSString* tLastStr = [tULRStr substringWithRange:NSMakeRange(tCutStart, [tULRStr length]-tCutStart)];
        NSArray* tCutArr = [tLastStr componentsSeparatedByString:@"&"];
        NSString* tStatusStr = nil;
        NSString* tMsgStr = nil;
        NSString* ttargetStr = nil;
        NSString* ttarget_uidStr = nil;
        NSString* tuser_idStr = nil;
        NSString* tprivate_codeStr = nil;
        for (NSString* tInStr in tCutArr) {
            NSArray* tKeyValue = [tInStr componentsSeparatedByString:@"="];
            if ([[tKeyValue objectAtIndex:0] isEqualToString:@"user_id"]) {
                tuser_idStr = [tKeyValue objectAtIndex:1];
            }else if([[tKeyValue objectAtIndex:0] isEqualToString:@"status"]){
                tStatusStr = [tKeyValue objectAtIndex:1];
            }else if([[tKeyValue objectAtIndex:0] isEqualToString:@"msg"]){
                tMsgStr = [tKeyValue objectAtIndex:1];
            }else if([[tKeyValue objectAtIndex:0] isEqualToString:@"target"]){
                ttargetStr = [tKeyValue objectAtIndex:1];
            }else if([[tKeyValue objectAtIndex:0] isEqualToString:@"privateCod"]){
                tprivate_codeStr = [tKeyValue objectAtIndex:1];
            }else if([[tKeyValue objectAtIndex:0] isEqualToString:@"target_uid"]){
                ttarget_uidStr = [tKeyValue objectAtIndex:1];
            }
        }
        if ([tStatusStr isEqualToString:@"success"]) {
            if ([tuser_idStr length] > 0) {
//                [self addHudLoad];
//                ASIHTTPRequest* tSinaRequest = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:@"http://interface.lvguo.com/interface.php?app=userNew&act=openLogin&user_id=%@&private_code=%@"]];
//                [tSinaRequest setDelegate:self];
//                [tSinaRequest setDidFailSelector:@selector(sinaLoginFail:)];
//                [tSinaRequest setDidFinishSelector:@selector(sinaLoginFinish:)];
//                [tSinaRequest startAsynchronous];
                return NO;
            }else if([ttarget_uidStr length] > 0){
                //注册
                RegisterViewController* tRegVC = [[RegisterViewController alloc] init];
                tRegVC.navigationItem.hidesBackButton =YES;
                tRegVC.m_Target = ttargetStr;
                tRegVC.m_Target_UID = ttarget_uidStr;
                [self.navigationController pushViewController:tRegVC animated:YES];
                [tRegVC release];
                return NO;
            }else{
                MainTabBarController* tMainTabController = (MainTabBarController*)self.navigationController.tabBarController;
                NSUserDefaults* tUserDef = [NSUserDefaults standardUserDefaults];
                
                if (m_BangType == 0) {
                    [tUserDef setObject:@"1" forKey:[NSString stringWithFormat:@"bangsina_%@",[tMainTabController.m_UserDic objectForKey:@"user_id"]]];
                }else{
                    [tUserDef setObject:@"1" forKey:[NSString stringWithFormat:@"bangqq_%@",[tMainTabController.m_UserDic objectForKey:@"user_id"]]];
                }
                [tUserDef synchronize];
                [_AppDel showWithCustomView:@"绑定成功" detailText:tMsgStr isCue:NO delayTime:2.f];
                [self.navigationController popViewControllerAnimated:NO];
                return NO;
            }
        }else{
            if (tMsgStr == nil || [tMsgStr isEqual:@""]) {
                [self.navigationController popViewControllerAnimated:NO];
                return NO;
            } else {
                [_AppDel showWithCustomView:tMsgStr detailText:@"" isCue:NO delayTime:2.f];
                [self.navigationController popViewControllerAnimated:NO];
                return NO;
            }
        }
        

        
    }
    return YES;
}

#pragma mark -
#pragma mark MBProgressHUDDelegate
- (void)hudWasHidden:(MBProgressHUD *)hud{
    _MBHUD.delegate = nil;
	[_MBHUD removeFromSuperview];
	[_MBHUD release];
	_MBHUD=nil;
}

-(void) addHudLoad{
	if (_MBHUD == nil) {
		_MBHUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
		// Add HUD to screen
		[self.navigationController.view addSubview:_MBHUD];
		// Regisete for HUD callbacks so we can remove it from the window at the right time
		_MBHUD.delegate = self;
		_MBHUD.labelText = @"请求数据中...";
		[_MBHUD show:YES];
	}
}

#pragma mark-
#pragma mark 代理登陆
-(void) sinaLoginFail:(ASIHTTPRequest*)request
{
    [_AppDel showWithCustomView:@"提示" detailText:@"网络错误请稍后再试!" isCue:YES delayTime:2.f];
}
-(void) sinaLoginFinish:(ASIHTTPRequest*)request
{
    NSString* tStrReq =[request responseString];
    NSLog(@"%@",tStrReq);
    NSError* tError;
    NSData *jsonData = [tStrReq dataUsingEncoding:NSUTF32BigEndianStringEncoding];
    NSDictionary *tDictionary = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&tError];
    int tErrorCode= [[tDictionary objectForKey:@"errorCode"] intValue];
    if (tErrorCode == 0) {
        NSMutableDictionary* tUserData = [NSMutableDictionary dictionary];
        NSUserDefaults* tUserDef = [NSUserDefaults standardUserDefaults];
        NSDictionary* data = [tDictionary objectForKey:@"data"];
        NSString* tCallStr = [data objectForKey:@"callback"];
        int tCutStart = [tCallStr rangeOfString:@"?"].location;
        tCutStart++;
        NSString* tLastStr = [tCallStr substringWithRange:NSMakeRange(tCutStart, [tCallStr length]-tCutStart)];
        NSArray* tCutArr = [tLastStr componentsSeparatedByString:@"&"];
        for (NSString* tInStr in tCutArr) {
            NSArray* tKeyValue = [tInStr componentsSeparatedByString:@"="];
            if ([[tKeyValue objectAtIndex:0] isEqualToString:@"user_id"]) {
                [tUserDef setObject:[tKeyValue objectAtIndex:1] forKey:@"user_id"];
                [tUserData setObject:[tKeyValue objectAtIndex:1] forKey:@"user_id"];
            }else if([[tKeyValue objectAtIndex:0] isEqualToString:@"email"]){
                [tUserData setObject:[tKeyValue objectAtIndex:1] forKey:@"email"];
            }else if([[tKeyValue objectAtIndex:0] isEqualToString:@"nickname"]){
                [tUserDef setObject:[tKeyValue objectAtIndex:1] forKey:@"nickname"];
                [tUserData setObject:[tKeyValue objectAtIndex:1] forKey:@"nickname"];
            }else if([[tKeyValue objectAtIndex:0] isEqualToString:@"avatar"]){
                [tUserDef setObject:[tKeyValue objectAtIndex:1] forKey:@"avatar"];
                [tUserData setObject:[tKeyValue objectAtIndex:1] forKey:@"avatar"];
            }else if([[tKeyValue objectAtIndex:0] isEqualToString:@"privateCod"]){
                [tUserDef setObject:[tKeyValue objectAtIndex:1] forKey:@"privateCod"];
                [tUserData setObject:[tKeyValue objectAtIndex:1] forKey:@"privateCod"];
            }
        }
        if (m_BangType == 0) {
            [tUserDef setObject:@"1" forKey:[NSString stringWithFormat:@"bangsina_%@",[tUserData objectForKey:@"user_id"]]];
        }else{
            [tUserDef setObject:@"1" forKey:[NSString stringWithFormat:@"bangqq_%@",[tUserData objectForKey:@"user_id"]]];
        }
        
        [tUserDef synchronize];
//        NSString* user_id =[data objectForKey:@"user_id"];
//        
//        
//        NSString* name = [data objectForKey:@"nickname"];
//        [tUserDef setObject:name forKey:@"nickname"];
//        
//        NSString* userurl = [data objectForKey:@"avatar"] ;
//        [tUserDef setObject:userurl forKey:@"avatar"];
//        
//        NSString* privateCod = [data objectForKey:@"privateCod"];
//        [tUserDef setObject:privateCod forKey:@"privateCod"];
        //登录成功
        MainTabBarController* tMainTabController = (MainTabBarController*)self.navigationController.tabBarController;
        tMainTabController.m_UserDic = tUserData;
        [tMainTabController loginOkToShowTag];
        
        [self.navigationController popViewControllerAnimated:NO];
    }else{
        [_AppDel showWithCustomView:[tDictionary objectForKey:@"errorMsg"] detailText:@"" isCue:NO delayTime:2.f];
    }
    [self hudWasHidden:nil];
}
@end
